import React, { useRef, useState } from 'react'
import Create from './componets/Create'
import Modal from 'antd/es/modal/Modal'
import ProTable from '@ant-design/pro-table'
import { Button, message, Tooltip } from 'antd'
import ProTableConfig from './ProTableConfig'
import { categoryList } from '@/services/category'
import { PageContainer } from '@ant-design/pro-layout'
import { QuestionCircleOutlined } from '@ant-design/icons'
import {
  cpTestList,
  deleteTestList,
  getTestList,
  hasUnitTest,
} from '@/services/testList'
import './index.less'
import GetTime from '@/components/GetTime'

const Index = () => {

  const [ids, setIds] = useState(undefined)
  const [subject, setSubject] = useState(undefined)
  const [isModalVisible, setIsModalVisible] = useState(false)
  const [testCategory, setTestCategory] = useState(undefined)
  const [selectedRowKeys, setSelectedRowKeys] = useState([])
  const [isCreateModalVisible, setIsCreateModalVisible] = useState(false)
  const [testListId, setTestListId] = useState(undefined)

  const actionRef = useRef()

  /**
   * 删除试卷
   * @param values
   */
  const delTestList = async (values) => {
    const response = await deleteTestList(values)
    if (response.status === undefined) {
      message.success('删除成功')
      setSelectedRowKeys([])
      setIds(undefined)
      // 刷新表格数据
      actionRef.current?.reload()
    }
  }

  /**
   * 复制试卷
   * @param value
   * @returns {Promise<void>}
   */
  const copyTestList = async (value) => {
    const response = await cpTestList(value)
    if (response.status === undefined) {
      message.success('复制成功')
      setSelectedRowKeys([])
      // 刷新表格数据
      actionRef.current?.reload()
    }
  }

  /**
   * 获取列表数据
   * @returns {Promise<{data}>}
   */
  const getData = async (params) => {
    // 更改默认属性名 current
    params = JSON.parse(JSON.stringify(params).replace(/current/g, 'page'))
    const response = await getTestList(params)
    const testCategory = await categoryList({ 'category_group': 'paper' })
    const subject = await categoryList({ 'category_group': 'subject' })
    let testCategoryArr = {}
    testCategory.map((item) => {
      testCategoryArr[item.id] = { text: item.name }
    })
    let subjectArr = {}
    subject.map((item) => {
      subjectArr[item.id] = { text: item.name }
    })
    setTestCategory(testCategoryArr)
    setSubject(subjectArr)
    return {
      data: response.data,
      success: true,
      total: response.meta.pagination.total,
    }
  }

  /**
   * 多选操作
   * @param selectedRowKeys
   */
  const onSelectChange = selectedRowKeys => {
    setSelectedRowKeys(selectedRowKeys)
  }

  /**
   * 多选配置
   * @type {{onChange: onSelectChange, selectedRowKeys: *[]}}
   */
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  }

  /**
   * 显示创建modal
   */
  const showCreateModal = () => {
    setIsCreateModalVisible(true)
  }

  /**
   * 显示删除modal
   * @param value
   */
  const showDelModal = (value) => {
    setIds(value)
    setIsModalVisible(true)
  }

  /**
   * 删除modal确认操作
   */
  const handleOk = () => {
    delTestList(ids)
    setSelectedRowKeys([])
    setIsModalVisible(false)
  }

  /**
   * 删除modal取消操作
   */
  const handleCancel = () => {
    setIsModalVisible(false)
  }

  /**
   * 导出试卷
   *
   * @param type
   * @param Tid 试卷id
   */
  const exportTest = async (type, Tid) => {
    const response = await hasUnitTest(Tid, type)
    const url = window.URL.createObjectURL(
      new Blob([response], { type: 'application/x-xls' }))
    // 创建 a 标签
    const link = document.createElement('a')
    link.style.display = 'none'
    link.href = url
    link.setAttribute('download', `test - ${Tid} - ${type}.xlsx`)
    document.body.appendChild(link)
    // 手动触发事件
    link.click()
    document.body.removeChild(link)
  }

  // 表头定义
  const columns = [
    {
      title: '试卷名称',
      dataIndex: 'name',
      copyable: true,
      ellipsis: true,
      width: '20%',
    },
    {
      title: '创建者',
      dataIndex: 'username',
      search: false,
      width: '8%',
    },
    {
      title: '分类名称',
      dataIndex: 'papername',
      search: false,
      align: 'center',
    },
    {
      title: '分类名称',
      dataIndex: 'paper_id',
      hideInTable: true,
      hideInForm: true,
      valueEnum: testCategory,
      align: 'center',
    },
    {
      title: '科目名称',
      search: false,
      dataIndex: 'subjectname',
      align: 'center',
    },
    {
      title: '科目名称',
      dataIndex: 'subject_id',
      hideInTable: true,
      hideInForm: true,
      valueEnum: subject,
      align: 'center',
    },
    {
      title: '状态',
      dataIndex: 'status',
      initialValue: 'all',
      align: 'center',
      width: '8%',
      search: false,
      valueEnum: {
        1: { text: '发布', status: 'Success' },
        0: { text: '未发布', status: 'Default' },
      },
    },
    {
      title: (<>
        创建时间
        <Tooltip placement="top" title="这是一段描述">
          <QuestionCircleOutlined style={{ marginLeft: 4 }}/>
        </Tooltip>
      </>),
      width: '10%',
      search: false,
      dataIndex: 'created_at',
      valueType: 'date',
      align: 'center',
      sorter: (a, b) => a.created_at - b.created_at,
    },
    {
      title: '导出试卷',
      width: '10%',
      valueType: 'option',
      align: 'center',
      render: (_, record) => [
        <a key="link"
           onClick={() => exportTest('noSuccess', record.id)}>无答案</a>,
        <a key="link2"
           onClick={() => exportTest('hasSuccess', record.id)}>有答案</a>,
      ],
    },
    {
      title: '试卷预览',
      search: false,
      width: '6%',
      align: 'center',
      render: (_, record) => [
        <a key="link" onClick={() => {
          /** todo 试卷预览 **/
          console.log(record.id)
        }}>预览</a>,
      ],
    },
    {
      title: '操作',
      width: 180,
      key: 'option',
      valueType: 'option',
      align: 'center',
      render: (_, record) => [
        <Button type="primary" size="small" key="primary"
                onClick={() => copyTestList(record.id)}
                style={{ background: '#f4a460', borderColor: '#f4a460' }}>
          复制
        </Button>,
        <Button type="primary" size="small" key="primary"
                style={{ marginLeft: -10 }}
                onClick={() => {
                  setTestListId(record.id)
                  showCreateModal()
                }}
        >
          编辑
        </Button>,
        <Button type="primary" size="small" key="primary"
                onClick={() => showDelModal(record.id)}
                style={{ marginLeft: -10 }} danger>
          删除
        </Button>,
      ],
    },
  ]

  return (
    <PageContainer header={{
      extra: [
        <GetTime key="getTime"/>,
      ],
    }}>
      <ProTable
        columns={columns}
        {...ProTableConfig}
        request={(params) => getData(params)}
        actionRef={actionRef}
        rowSelection={rowSelection}
        rowKey="id"
        options={{ fullScreen: false, reload: true, setting: false }}
        search={{
          layout: 'vertical',
          defaultCollapsed: false,
        }}
        dateFormatter="string"
        toolbar={{
          title: '试卷列表',
        }}
        toolBarRender={() => [
          <Button type="primary" key="primary"
                  onClick={() => showCreateModal(true)}>
            创建试卷
          </Button>,
          <Button type="primary" key="primary" danger onClick={() => {
            selectedRowKeys[0]
              ? showDelModal(selectedRowKeys)
              : message.error('未选择试卷')
          }
          }>
            批量删除
          </Button>,
        ]}/>
      <Modal title="删除试卷" visible={isModalVisible} centered={true}
             onOk={handleOk} onCancel={handleCancel}>
        <p>确定要删除试卷吗</p>
      </Modal>
      <Create
        isCreateModalVisible={isCreateModalVisible}
        subject={subject}
        setIsCreateModalVisible={setIsCreateModalVisible}
        actionRef={actionRef}
        testListId={testListId}
        setTestListId={setTestListId}
      />
    </PageContainer>
  )
}

export default Index
